


#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv2\core\core.hpp>
#include "Utils.h"


bool  ProximoLimite(const cv::Point pt,const int width, const int height)
{
	int distStartX = pt.x;
	int distEndX = std::abs(pt.x - width);
	int distStartY = pt.y;
	int distEndY = std::abs(pt.y - height);

	return distStartX < 5  || distEndX <5 || distStartY < 5 || distEndY <5;


}

cv::Mat DetectaLinhasHough(const cv::Mat &img,cv::Rect charRoi)
{
	cv::Rect charRoiExtra = cv::Rect(charRoi.x-15,charRoi.y-10,charRoi.width+25,charRoi.height+20);
	cv::Mat imLines = cv::Mat::zeros(img.size(),0);

	

#if 0
		vector<Vec2f> lines;
		HoughLines(dst, lines, 1, CV_PI/180, 60, 0, 0 );

		for( size_t i = 0; i < lines.size(); i++ )
		{
			float rho = lines[i][0], theta = lines[i][1];
			Point pt1, pt2;
			double a = cos(theta), b = sin(theta);
			double x0 = a*rho, y0 = b*rho;
			pt1.x = cvRound(x0 + 1000*(-b));
			pt1.y = cvRound(y0 + 1000*(a));
			pt2.x = cvRound(x0 - 1000*(-b));
			pt2.y = cvRound(y0 - 1000*(a));
			line( cdst, pt1, pt2, Scalar(0,0,255), 1, CV_AA);
		}
	#else
		std::vector<cv::Vec4i> lines;
		//HoughLinesP(dst, lines, 1, CV_PI/180,50,85, 10 );
		cv::HoughLinesP(img,lines,1,CV_PI/180,50,50, 10 );
		
		for( size_t i = 0; i < lines.size(); i++ )
		{
			cv::Vec4i line = lines[i];		
			
			cv::Point ptStart = cv::Point(line[0], line[1]);
			cv::Point ptEnd = cv::Point(line[2], line[3]);

			

			if(!ProximoLimite(ptStart,img.cols,img.rows) && !ProximoLimite(ptEnd,img.cols,img.rows))//
				continue;

			if(ptStart.inside(charRoiExtra) && ptEnd.inside(charRoiExtra))
				continue;

			cv::line( imLines, ptStart, ptEnd, cv::Scalar(255), 2, 4);
		}
		
		//cv::Mat imFinal = img-imLines;

		//cv::rectangle(imFinal,charRoi,cv::Scalar(127));

		//cv::threshold(imLines,imLines,225,255,cv::THRESH_BINARY);
		//cv::imshow("29",img);
		//cv::imshow("28",imLines);
		//cv::imshow("30",imFinal);
		//cv::waitKey();
	#endif

	

	return imLines;
}


cv::Mat RemoveLinhas(const cv::Mat&im,const cv::Rect& roi)
{	
	cv::Mat imLinhas = ::DetectaLinhasHough(im,roi);

	cv::Mat imOut = im - imLinhas;

	
	static int cont = 0 ;	
//	cv::imwrite("d:\\"+Utils::to_string(cont)+".bmp",im);
//	cv::imwrite("d:\\"+Utils::to_string(cont)+"-.bmp",imLinhas);
//	cv::imwrite("d:\\"+Utils::to_string(cont)+"--.bmp",imOut);
	cont ++;


	return imOut;
}